import { Component, OnInit, forwardRef, Input } from '@angular/core'
import { FormGroup, FormBuilder, ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'

import { FieldBase } from './field-base.interface'

@Component({
  selector: 'app-channel-form',
  templateUrl: './channel-form.component.html',
  styles: [],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => ChannelFormComponent),
      multi: true,
    },
  ],
})
export class ChannelFormComponent implements OnInit, ControlValueAccessor {
  constructor(
    private fb: FormBuilder,
  ) { }

  @Input() fields: FieldBase<any>[] = []

  @Input() form: FormGroup = this.fb.group({})

  onTouched: () => void = () => {}

  writeValue(val: any): void {
    this.form.setValue(val, { emitEvent: false })
  }

  registerOnChange(fn: any): void {
    this.form.valueChanges.subscribe(fn)
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn
  }

  setDisabledState?(isDisabled: boolean): void {
    isDisabled ? this.form.disable() : this.form.enable()
  }

  ngOnInit() {}
}
